<template>
  <div id="personal_timetable">
    <div class="info_title">
      我的课表
      <el-input
        style="width: 3rem;float:right;margin-top:-0.06rem;"
        placeholder="搜索 课程名称"
        suffix-icon="el-icon-search"
        v-model="keyWords"
        class="input_search"
      ></el-input>
    </div>
    <!--课程安排表-->
    <div class="classTableBox">
      <el-row class="toprow">
        <i class="el-icon-arrow-left btn" @click="reduceTime()"></i>
        <span class="timetxt">{{currentyear}}年{{currentmonth}}月</span>
        <i class="el-icon-arrow-right btn" @click="addTime()"></i>
      </el-row>
      <div class="table_box">
        <table class="table" cellspacing="0">
          <thead class="thead">
            <tr>
              <td>周日</td>
              <td>周一</td>
              <td>周二</td>
              <td>周三</td>
              <td>周四</td>
              <td>周五</td>
              <td>周六</td>
            </tr>
          </thead>
          <tbody class="tbody">
            <tr v-for="tdItem in trList">
              <td v-for="item in tdItem.td" :class="{box_active:item.isCurrent}">
                <div
                  class="box_index"
                  :class="[{box_index_current:item.isshowCurrent},{ box_index_no:item.isNoDate}]"
                >{{item.index}}</div>
                <!--当天课程只有一节的时候-->
                <div
                  class="table_select_box table_box_active"
                  v-if="item.isHasClass && item.classList.length == 1"
                  @click="gotoClass(item.classList[0])"
                  :class="{table_box_currActive:item.isCurrent}"
                  :title="item.classList[0].showTime+'\n'+item.classList[0].className+'\n'+item.classList[0].courseName+'('+item.classList[0].orderBy+'/'+item.classList[0].classCourseCount+')'+'\n'+item.classList[0].teacherUserName+'\n'+item.classList[0].classroomName"
                >
                  <div class="box_item">{{item.classList[0].showTime}}</div>
                  <div class="box_item">{{item.classList[0].courseName}}</div>
                  <div class="box_item">{{item.classList[0].className}}</div>
                  <div class="box_item">{{item.classList[0].teacherUserName}}</div>
                </div>
                <!--当天课程二节的时候-->
                <div v-else-if="item.isHasClass && item.classList.length == 2">
                  <div
                    v-for="classs in item.classList"
                    :key="classs.classSyllabusId"
                    class="table_select_box1 table_box_active"
                    @click="gotoClass(classs)"
                    :class="{table_box_currActive:item.isCurrent}"
                    :title="classs.showTime+'\n'+classs.className+'\n'+classs.courseName+'('+classs.orderBy+'/'+classs.classCourseCount+')'+'\n'+classs.teacherUserName+'\n'+classs.classroomName"
                  >
                    <div class="box_item">{{classs.showTime}}</div>
                    <div class="box_item">{{classs.courseName}}</div>
                  </div>
                </div>
                <!--当天课程只有三节及以上的时候-->
                <div v-else-if="item.isHasClass && item.classList.length >= 3" class="more_box">
                  <div
                    v-for="classs in item.classList"
                    :key="classs.classSyllabusId"
                    class="table_select_box2 table_box_active"
                    @click="gotoClass(classs)"
                    :class="{table_box_currActive:item.isCurrent}"
                    :title="classs.showTime+'\n'+classs.className+'\n'+classs.courseName+'('+classs.orderBy+'/'+classs.classCourseCount+')'+'\n'+classs.teacherUserName+'\n'+classs.classroomName"
                  >
                    <div class="box_item">{{classs.showTime}}</div>
                    <div class="box_item">{{classs.courseName}}</div>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { constants } from "fs";
let vm;
export default {
  data: function() {
    return {
      trList: [],
      timeList: [],
      classList: [],
      currentday: "",
      currentyear: "",
      currentmonth: "",
      currentDate: "",
      keyWords: ""
    };
  },
  watch: {
    // 如果 `keyWords` 发生改变，这个函数就会运行
    keyWords: function(newSearchText, oldSearchText) {
      console.log(newSearchText);
      let daynum = vm.getDaynum(vm.currentyear, vm.currentmonth); //当前月份的天数
      let paras = {
        keyWords: newSearchText,
        startTime: vm.currentyear + "-" + vm.currentmonth + "-01 00:00:00",
        endTime:
          vm.currentyear + "-" + vm.currentmonth + "-" + daynum + " 23:59:59"
      };
      vm.getData(paras);
    }
  },
  methods: {
    gotoClass(item) {
      switch (item.status) {
        case "即将开始":
          if (item.studentUrl == null || item.studentUrl == "") {
            this.$alert("该课节暂无上课视频，请稍后再试!", "暂无视频", {
              confirmButtonText: "确定",
              type: "warning",
              center: true,
              callback: action => {}
            });
          } else {
            window.open(item.studentUrl, "_blank");
          }
          break;
        case "未学习":
          this.$alert(
            "该课节的上课时间是：" +
              item.startTime +
              "\n请提前20分钟进入教室上课",
            "等待上课",
            {
              confirmButtonText: "确定",
              type: "warning",
              center: true,
              callback: action => {}
            }
          );
          break;
        case "正在上课":
          if (item.studentUrl == null || item.studentUrl == "") {
            this.$alert("该课节暂无上课视频，请稍后再试!", "暂无视频", {
              confirmButtonText: "确定",
              type: "warning",
              center: true,
              callback: action => {}
            });
          } else {
            if (!tool.isChrome()) {
              this.$alert("小鳄鱼课堂仅支持谷歌浏览器", "小鳄鱼课堂", {
                confirmButtonText: "谷歌浏览器下载",
                type: "warning",
                center: true
              })
                .then(() => {
                  window.open("https://www.google.cn/chrome/");
                })
                .catch(() => {});
            } else {
              window.open(item.studentUrl, "_blank");
            }
          }
          break;
        case "完成":
          if (item.playUrl == null || item.playUrl == "") {
            this.$alert("该课节暂无回放视频", "暂无视频", {
              confirmButtonText: "确定",
              type: "warning",
              center: true,
              callback: action => {}
            });
          } else {
            window.open(item.playUrl, "_blank");
          }
          break;
        default:
      }
    },
    reduceTime() {
      if (vm.currentmonth == 1) {
        vm.currentyear--;
        vm.currentmonth = 12;
      } else {
        vm.currentmonth--;
      }
      vm.currentmonth =
        vm.currentmonth > 9 ? vm.currentmonth : "0" + vm.currentmonth;
      let daynum = vm.getDaynum(vm.currentyear, vm.currentmonth); //当前月份的天数
      let paras = {
        startTime: vm.currentyear + "-" + vm.currentmonth + "-01 00:00:00",
        endTime:
          vm.currentyear + "-" + vm.currentmonth + "-" + daynum + " 23:59:59"
      };
      vm.getData(paras);
    },
    addTime() {
      if (vm.currentmonth == 12) {
        vm.currentyear++;
        vm.currentmonth = 1;
      } else {
        vm.currentmonth++;
      }
      vm.currentmonth =
        vm.currentmonth > 9 ? vm.currentmonth : "0" + vm.currentmonth;
      let daynum = vm.getDaynum(vm.currentyear, vm.currentmonth); //当前月份的天数
      let paras = {
        startTime: vm.currentyear + "-" + vm.currentmonth + "-01 00:00:00",
        endTime:
          vm.currentyear + "-" + vm.currentmonth + "-" + daynum + " 23:59:59"
      };
      vm.getData(paras);
    },
    init() {
      let data = new Date();
      vm.currentday =
        data.getDate() > 9 ? data.getDate() : "0" + data.getDate(); //获取当前日
      vm.currentyear = data.getFullYear(); //获取当前年
      vm.currentmonth =
        data.getMonth() + 1 > 9
          ? data.getMonth() + 1
          : "0" + (data.getMonth() + 1); //获取当前月（现实月份）
      let daynum = vm.getDaynum(vm.currentyear, vm.currentmonth); //当前月份的天数
      let paras = {
        startTime: vm.currentyear + "-" + vm.currentmonth + "-01 00:00:00",
        endTime:
          vm.currentyear + "-" + vm.currentmonth + "-" + daynum + " 23:59:59"
      };
      vm.getData(paras);
    },
    getData(paras) {
      api.StudentSyllabus(paras).then(function(data) {
        if (data.resultCode == 2000) {
          vm.classList = data.listSyllabus == null ? [] : data.listSyllabus;
        } else {
          tool.message({
            showClose: true,
            message: data.message,
            type: "warning"
          });
        }
        vm.getCalender(vm.currentyear, vm.currentmonth);
      });
    },
    /**
     *  返回传递月份的天数
     * @param {Object} year 年份
     * @param {Object} month 月份(现实月份)
     */
    getDaynum(year, month) {
      var tianShu;
      if (
        month == 1 ||
        month == 3 ||
        month == 5 ||
        month == 7 ||
        month == 8 ||
        month == 10 ||
        month == 12
      ) {
        tianShu = 31;
      } else if (month != 2) {
        tianShu = 30;
      } else {
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
          tianShu = 29;
        } else {
          tianShu = 28;
        }
      }
      return tianShu;
    },
    /**
     * 计算日历中的显示数据
     */
    getCalender(year, month) {
      vm.timeList = [];
      vm.trList = [];
      let daynum = vm.getDaynum(year, month); //当前月份的天数
      let str = year + "/" + month + "/1";
      let xingqi = new Date(str.replace(/-/g, "/")).getDay(); //当前月份第一天是星期几
      let current_day = 0;
      let olddaynum = vm.getDaynum(year, month - 1); //上一个月的天数
      let last_day = xingqi;
      let next_day = 0; //下一个月的起始天数
      let data = new Date();
      let days = data.getDate() > 9 ? data.getDate() : "0" + data.getDate(); //获取当前日
      let years = data.getFullYear(); //获取当前年
      let months =
        data.getMonth() + 1 > 9
          ? data.getMonth() + 1
          : "0" + (data.getMonth() + 1); //获取当前月（现实月份）
      for (let i = 0; i < 42; i++) {
        if (i >= xingqi && current_day < daynum) {
          current_day++;
          let current_date =
            vm.currentyear +
            "-" +
            vm.currentmonth +
            "-" +
            (current_day > 9 ? current_day : "0" + current_day);

          let classList = [];
          let isCurrent = false;
          let isHasClass = false;
          let isshowCurrent = false;
          let currentshowDate = years + "-" + months + "-" + days;
          if (currentshowDate == current_date) isshowCurrent = true;
          for (let i = 0; i < vm.classList.length; i++) {
            vm.classList[i].status = "";
            if (vm.classList[i].attendMode == 1) {
              vm.classList[i].status = "完成";
            } else {
              if (vm.getStatus(vm.classList[i].startTime) > 0) {
                vm.classList[i].status =
                  vm.getStatus(vm.classList[i].startTime) <= 1200
                    ? "即将开始"
                    : "未学习";
              } else {
                vm.classList[i].status =
                  vm.getStatus(vm.classList[i].endTime) > 0
                    ? "正在上课"
                    : "完成";
              }
            }
            let classDate = vm.classList[i].startTime.split(" ")[0];
            console.log(classDate, current_date);
            if (classDate == current_date) {
              vm.classList[i].showTime =
                vm.classList[i].startTime.split(" ")[1] +
                "-" +
                vm.classList[i].endTime.split(" ")[1];
              isHasClass = true;
              classList.push(vm.classList[i]);
              if (current_date == currentshowDate) {
                isCurrent = true;
              }
            }
          }
          vm.timeList.push({
            isshowCurrent: isshowCurrent, //是否高亮日期
            index: current_day,
            isCurrent: isCurrent, //是否是当天
            isHasClass: isHasClass, //是否有课
            isNoDate: false, //不在本月内
            classList: classList.sort(vm.sortBy("startTime", true)) //课程列表
          });
        } else {
          if (xingqi > 0 && current_day < daynum) {
            last_day--;
            vm.timeList.push({
              index: olddaynum - last_day,
              isCurrent: false,
              isHasClass: false,
              isNoDate: true
            });
          }
          if (current_day >= daynum) {
            next_day++;
            vm.timeList.push({
              index: next_day,
              isCurrent: false,
              isHasClass: false,
              isNoDate: true
            });
          }
        }
      }
      vm.getTrList();
    },
    getStatus(startTime) {
      let startTime1 = new Date();
      console.log(startTime1);
      //定义结束时间
      let endTime = new Date(startTime.replace(/-/g, "/"));
      console.log(endTime);
      //算出中间差并且已毫秒数返回; 除以1000将毫秒数转化成秒数方便运算；
      let countDown = (endTime.getTime() - startTime1.getTime()) / 1000;
      console.log(countDown);
      return countDown;
    },
    sortBy: function(attr, rev) {
      //第二个参数没有传递 默认升序排列
      if (rev == undefined) {
        rev = 1;
      } else {
        rev = rev ? 1 : -1;
      }

      return function(a, b) {
        let attrA = a[attr].replace("-", "/");
        let attrB = b[attr].replace("-", "/");
        a = new Date(attrA.replace(/-/g, "/"));
        b = new Date(attrB.replace(/-/g, "/"));
        if (a < b) {
          return rev * -1;
        }
        if (a > b) {
          return rev * 1;
        }
        return 0;
      };
    },
    getTrList() {
      let tempList = [];
      let index = 0;
      for (let i = 0; i < vm.timeList.length; i++) {
        index++;
        tempList.push(vm.timeList[i]);
        if (index % 7 == 0 && index != 0) {
          vm.trList.push({
            td: tempList
          });
          tempList = [];
        }
      }
    }
  },
  created: function() {
    vm = this;
    vm.init();
  }
};
</script>

<style scoped src="../../style/module/table_calender.css"></style>
<style lang="scss">
#personal_timetable {
  height: 100%;
  width: 100%;
  margin-bottom: 0.2rem;
  .info_title {
    border-radius: 8px;
    background: #ffffff;
    padding: 0.2rem 0.34rem 0.2rem;
    font-size: 0.2rem;
    color: #333333;
    .input_search {
      .el-input__inner {
        background-color: rgb(247, 248, 250);
      }
    }
  }

  .classTableBox {
    margin-top: 0.1rem;
    height: 6.72rem;
    background: #fff;
    border-radius: 8px;
    .toprow {
      text-align: center;
      user-select: none;
      padding-top: 0.2rem;
      font-size: 0.16rem;
      color: #333333;
      .timetxt {
        margin: 0 0.5rem;
      }
      .btn:hover {
        cursor: pointer;
        color: #37a169;
      }
    }
    .table_box {
      width: 100%;
      margin-left: 0.06rem;
      font-size: 0.12rem;
      .box_active {
        border: 1px dashed #33d57c;
      }
      .box_index {
        position: absolute;
        font-weight: bold;
        top: 0.04rem;
        right: 0.12rem;
        color: #666666;
      }
      .box_index_no {
        color: #999999;
      }
      .box_index_current {
        color: #37a169;
      }
      .table_select_box1 {
        cursor: pointer;
        width: 1.24rem;
        height: 0.44rem;
        margin-bottom: 0.02rem;
        .box_item {
          font-size: 0.12rem;
          width: 100%;
          height: 0.2rem;
          line-height: 0.2rem;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          padding-left: 0.06rem;
        }
      }
      /*滚动条*/
      .more_box::-webkit-scrollbar {
        width: 0rem;
      }

      .more_box {
        overflow-y: auto;
        overflow-x: hidden;
        height: 0.94rem;
        width: 1.3rem;
      }
      .table_select_box2 {
        cursor: pointer;
        width: 1.24rem;
        height: 0.28rem;
        margin-bottom: 0.01rem;
        .box_item {
          font-size: 0.12rem;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          line-height: 0.14rem;
          width: 100%;
          height: 0.14rem;
          padding-left: 0.06rem;
        }
      }
      .table_select_box {
        width: 1.24rem;
        height: 0.86rem;
        cursor: pointer;
        padding-top: 0.2rem;
        .box_item {
          font-size: 0.12rem;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          line-height: 0.15rem;
          width: 100%;
          height: 0.15rem;
          padding-left: 0.06rem;
        }
      }
    }
  }

  .table_box_active {
    border-left: 2px solid #6dbffd;
    color: #2aaeee;
    background: #e9f5fc;
  }
  .table_box_currActive {
    border-left: 2px solid #33d57c;
    color: #33d57c;
    background: #ebf8f1;
  }
}
</style>